<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('membership_codes', function (Blueprint $table) {
            $table->id();
            $table->string('code', 32)->unique()->comment('兑换码');
            $table->enum('type', ['day', 'month', 'year', 'permanent'])->comment('会员类型：日卡、月卡、年卡、永久卡');
            $table->integer('duration')->nullable()->comment('时长（天数），永久卡为null');
            $table->boolean('is_used')->default(false)->comment('是否已使用');
            $table->unsignedBigInteger('used_by')->nullable()->comment('使用者用户ID');
            $table->timestamp('used_at')->nullable()->comment('使用时间');
            $table->timestamp('expires_at')->nullable()->comment('兑换码过期时间');
            $table->timestamps();
            
            $table->foreign('used_by')->references('id')->on('users')->onDelete('set null');
            $table->index(['code', 'is_used']);
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('membership_codes');
    }
};